package com.jsj.servlet.ch4;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/shoppingCar")
public class ShoppingCarServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		
		//获取会话对象
		HttpSession session=request.getSession();
		
		Map<String,Integer> car= (Map<String, Integer>) session.getAttribute("shoppingCar");
		if(car == null) {
			car=new HashMap<String,Integer>();
		}
		//获取从页面获取的书籍数据
		String[] books=request.getParameterValues("book");
		if(books !=null && books.length>0) {
			for(String bookName:books) {
				if(car.get(bookName) != null) {
					int num=car.get(bookName);
					car.put(bookName, num+1);
				}else {
					car.put(bookName, 1);
				}
			}
		}
		//将更新后的购物车存储在会话域中
		session.setAttribute("shoppingCar", car);
		session.setAttribute("username", "tom");
		response.sendRedirect("shoppingList");
		
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
}
